library(xcore)
library(tidyverse)
library(ExperimentHub)

eh <- ExperimentHub()
query(eh, "xcoredata")

# transform gene count to fantom promoter count ------------
promoters_f5_core <- xcoredata::promoters_f5_core()
remap_promoters_f5 <- xcoredata::remap_promoters_f5()

symbol2fantom <- eh[["EH7700"]]

hek293 <- read_csv('mission/FPP/thapsigargin_upr/GSE293666_HEK293_IRE1_activators_raw_counts_all_samples.csv.gz')

tg293 <- hek293 |>
  select(matches('Name|DMSO|Tg')) |>
  column_to_rownames('Name') |>
  mutate(across(everything(), as.integer)) |>
  as.matrix()

head(tg293)

fantom293 <- tg293 |> translateCounts(symbol2fantom)

head(fantom293)

design293 <- tibble(sample = colnames(tg293),
       DMSO = str_count(sample, 'DMSO'),
       Tg = str_count(sample, 'Tg')) |>
  column_to_rownames('sample') |>
  as.matrix()

# create Multi-Assay Experiment from promoter count matrix ------------
mae <- fantom293 |>
  prepareCountsForRegression(design = design293, base_lvl = "DMSO")

# load signature refs --------
## remap promoter ref
remap_promoters_f5 <- eh[["EH7301"]]

## a binary sparse matrix of 1.6 GB
remap_promoters_f5[1:5, 1:5]

# it is ok to use a subset of sig ref
mae <- addSignatures(mae, remap = remap_promoters_f5)

mae <- filterSignatures(mae, min = 0.05, max = 0.95)

# compute TF activity -------------
# register parallel backend
# 16 worker cost ~2min for total remap ref
doParallel::registerDoParallel(16L)
BiocParallel::register(BiocParallel::DoparParam(), default = TRUE)

res <- modelGeneExpression(
  mae = mae,
  xnames = "remap",
  nfolds = 5)

res$results$remap |>
  as_tibble() |>
  filter(str_detect(name, 'SREBF'))

res$results$remap |>
  as_tibble() |>
  mutate(scaled_tg = scale(Tg))

remap_promoters_f5 |> colnames() |>
  str_subset('SREBF')
